import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.jdom.Document;
import org.jdom.Attribute;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.json.JSONObject;
import org.json.JSONArray;
import java.net.URL;
import java.net.URLEncoder;

public class MovieSearchServlet extends HttpServlet {
	
	public void doGet(HttpServletRequest request, 
	HttpServletResponse response)
	throws IOException, ServletException
	{  
		response.setContentType("text/json");
	        PrintWriter out = response.getWriter();

	String title = new String(request.getParameter("title"));
	String title_encoded = URLEncoder.encode(title, "UTF-8");
	String title_type = new String(request.getParameter("title_type"));
	URL url = new URL("http://cs-server.usc.edu:19927/cgi-bin/get_movies_xml.pl?title="+title_encoded+"&title_type="+title_type);
	SAXBuilder builder = new SAXBuilder();
	try {
		Document document = (Document) builder.build(url.openStream());
		Element rootNode = document.getRootElement();
		Element resultsNode = rootNode.getChild("results");
		JSONObject results = new JSONObject();
		List list = resultsNode.getChildren("result");
		JSONObject result = new JSONObject();
		results.put("results", result);
		JSONArray array = new JSONArray();
		result.put("result", array);
		

		for (int i = 0; i < list.size(); i++) {
			Element node = (Element) list.get(i);
			JSONObject resattr = new JSONObject();
			List attributes = node.getAttributes();
			for (int j = 0; j < attributes.size(); j++) {
				Attribute attr = (Attribute) attributes.get(j);
				resattr.put(attr.getName(), attr.getValue()); //Dynamically adds key-value pairs to object
			   	//out.println(attr.getName());
				//out.println(attr.getValue());
			}
			array.put(i, resattr);
		}
		out.println(results);
 	} catch (IOException io) {
		System.out.println(io.getMessage());
	} catch (JDOMException jdomex) {
		System.out.println(jdomex.getMessage());
	}
	}
	

	
}
